<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning">
      </el-alert>
      <div class="block">
        <span class="demonstration">选择商品分类:</span>
        <el-cascader
          :options="parentCatList"
          :props="cascaderProps"
          @change="handleChange"
          change-on-select
          clearable expand-change="hover"
          v-model="selectedKeys"></el-cascader>
      </div>
      <!--标签页-->
      <template>
        <el-tabs @tab-click="handleClick" v-model="activeName">
          <el-tab-pane label="动态参数" name="many">
            <el-button :disabled="isBtnDisabled" @click="addParamDialogVisible"
                       type="primary">添加分类
            </el-button>
            <el-table
              :data="manyTableData"
              border
              stripe
              style="width: 100%">
              <!--展开行-->
              <el-table-column
                type="expand">
                <template slot-scope="scope">
                  <el-tag closable  @close="tagClose(i , scope.row)" :key="i" v-for="(item ,i) in scope.row.attr_vals">
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column
                label="#"
                type="index">
              </el-table-column>
              <el-table-column
                label="参数名称"
                prop="attr_name">
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="scope">
                  <el-button @click="showeditdialog(scope.row.attr_id)" icon="el-icon-edit" size="mini"
                             type="primary">编辑
                  </el-button>
                  <el-button @click="open(scope.row.attr_id)" icon="el-icon-delete" size="mini"
                             type="danger">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button :disabled="isBtnDisabled" @click="addParamDialogVisible"
                       type="primary">添加属性
            </el-button>
            <el-table
              :data="onlyTableData"
              border
              stripe
              style="width: 100%">
              <!--展开行-->
              <el-table-column
                type="expand">
                <template slot-scope="scope">
                  <el-tag closable  @close="tagClose(scope.row)" :key="i" v-for="(item ,i) in scope.row.attr_vals">
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column
                label="#"
                type="index">
              </el-table-column>
              <el-table-column
                label="属性名称"
                prop="attr_name">
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="scope">
                  <el-button @click="showeditdialog(scope.row.attr_id)" icon="el-icon-edit" size="mini"
                             type="primary">编辑
                  </el-button>
                  <el-button @click="open(scope.row.attr_id)" icon="el-icon-delete" size="mini"
                             type="danger">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!--添加用户的对话框-->
    <el-dialog
      :title="'添加' + addTitleName"
      :visible.sync="dialogVisible"
      @close="addDialogClosed('addFormRef')"
      width="50%">
      <el-form :model="addForm" :rules="addFormRules" label-width="15%" ref="addFormRef">
        <el-form-item :label="addTitleName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button @click="addParams" type="primary">确 定</el-button>
  </span>
    </el-dialog>

    <!--编辑用户的对话框-->
    <el-dialog
      :title="'修改' + addTitleName"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed('editFormRef')"
      width="50%">
      <el-form :model="editForm" :rules="editFormRules" label-width="15%" ref="editFormRef">
        <el-form-item :label="addTitleName" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button @click="editParams" type="primary">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: 'params',
  data () {
    return {
      parentCatList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: [],
      activeName: 'many',
      dialogVisible: false,
      editDialogVisible: false,
      paramData: [],
      manyTableData: [],
      onlyTableData: [],
      addTitleName: '',
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            tigger: 'blur'
          }
        ]
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            tigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    handleChange (value) {
      if (this.activeName === 'many') {
        this.addTitleName = '动态参数'
      } else {
        this.addTitleName = '静态属性'
      }
      this.getParamData()
    },
    handleClick (tab, event) {
      this.getParamData()
    },
    async getparentCatList () {
      //获取父级分类数据列表
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.parentCatList = res.data
    },
    //监听对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    addParamDialogVisible () {
      this.dialogVisible = true
    },
    async showeditdialog (attr_id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log(res.data)
      this.editForm = res.data
    },
    open (id) {
      console.log('laile')
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.getParamData()
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async getParamData () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //获取动态参数数据列表
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      //控制文本框的显示与隐藏
        item.inputVisible = false
        //文本框中输入的值
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      //this.paramData = res.data
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        } else {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
          }
          this.dialogVisible = false
          this.getParamData()
        }
      })
    },
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        } else {
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
          }
          this.editDialogVisible = false
          this.getParamData()
        }
      })
    },
    async tagClose(i ,row){
      row.attr_vals.splice(i , 1)
      //发起请求
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
      }
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    async handleInputConfirm(row) {
      row.inputVisible = false
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      console.log(row.inputValue.trim())
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //发起请求
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
      }
    }
  },
  computed: {
    //如果按钮需要被禁用，则返回true,否则返回false
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      } else {
        return null
      }
    }
  },
  created () {
    this.getparentCatList()
  }
}
</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 15px;
    font-size: 12px;
  }

  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  }

  .el-cascader {
    margin-left: 15px;
    width: 300px;
  }

  .el-alert {
    margin-bottom: 15px;
  }

  .el-button {
    margin-bottom: 15px;
  }
  .el-tag{
    margin-right: 10px;
  }
  .input-new-tag{
    width: 120px;
  }
</style>
